package a02_链表;

/**
 * <p>
 * a04_两两交换链表中的节点
 * </p>
 *
 * @author flyduck
 * @since 2024-06-18
 */
public class a05_两两交换链表中的节点复习4 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        ListNode listNode = swapPairs(head);
        print(listNode);
    }

    private static void print(ListNode listNode) {
        ListNode temp = listNode;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
        System.out.println("================");
    }


    public static ListNode swapPairs(ListNode head) {
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode currentNode = dummyNode;
        while (currentNode != null && currentNode.next != null && currentNode.next.next != null) {
            ListNode firstNode = currentNode.next;
            ListNode secondNode = firstNode.next;
            ListNode thirdNode = secondNode.next;

            currentNode.next = secondNode;
            secondNode.next = firstNode;
            firstNode.next = thirdNode;

            currentNode =  firstNode;
        }
        return dummyNode.next;

    }
}
